﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Common.Extensions;
using Windows.UI.Xaml.Shapes;
using Windows.UI;
using Common.UI.Controls.Utils;

// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236

namespace Common.UI.Controls
{
	public sealed partial class DateTimeChart : UserControl
	{
		public DateTimeChart()
		{
			this.InitializeComponent();

			var timer = new DispatcherTimer();
			timer.Interval = TimeSpan.FromMilliseconds(50);
			timer.Tick += timer_Tick;
			timer.Start();
		}

		void timer_Tick(object sender, object e)
		{
			Update();
		}

		public DateTimeChartItemsSource Source
		{
			get { return (DateTimeChartItemsSource)GetValue(SourceProperty); }
			set { SetValue(SourceProperty, value); }
		}

		public static readonly DependencyProperty SourceProperty =
			DependencyProperty.Register("Source", typeof(DateTimeChartItemsSource), typeof(DateTimeChart), new PropertyMetadata(null, OnSourceChanged));

		private static void OnSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
		{
			(d as DateTimeChart).Update();
		}

		private void UserControl_SizeChanged(object sender, SizeChangedEventArgs e)
		{
			Update();
		}

		private void Update()
		{
			lock (this)
			{
				Update(ActualHeight, ActualWidth);
			}
		}

		private void Update(double ActualHeight, double ActualWidth)
		{
			Canva.Children.Clear();

			if (Source == null || Source.Items.IsNullOrEmpty() || (ActualHeight < 0.1 && ActualWidth < 0.1))
				return;

			var barWidth = 2;

			foreach (var item in Source.Items)
			{
				var value = item.Value;
				var date = item.Key;				
				

				var barHeight = Source.ValueProprtion(value, 1.0) * ActualHeight;
				var valueProportion = Source.DateProportion(date, 0.0) * ActualWidth;

				var left = valueProportion - (barWidth / 2.0);

				var rect = new Rectangle()
				{
					Fill = value == Source.MaxValue ? new SolidColorBrush(Colors.Red) : this.Foreground,
					Width = barWidth,
					Height = barHeight,
				};
				Canvas.SetLeft(rect, left);
				Canvas.SetTop(rect, ActualHeight - barHeight);

				Canva.Children.Add(rect);
			}
		}
	}

	
}
